
addEvent("cmta_login:checklogin", true)
addEventHandler("cmta_login:checklogin", resourceRoot, function(login,pass)
	local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE login=?", login)
    if result and #result > 0 then
        local resultblock=exports["cmta-db"]:dbGet("SELECT * FROM cmta_bans WHERE uid=?", result[1]["id"])
        if resultblock and #resultblock > 0 then
        if resultblock[1]["type"] == "blokada konta" then
            exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Upss...\n#ffffffTo konto jest zablokowane.\nWyjaśnij to na forum.","error",4000)
            return
        end
        end

        if result[1].login == login and result[1].password == teaEncode(pass,"R{e+=j8'a!EqUT7UKHJS,(E[txHjj35;9aP:l;QjNIpK0$r:Q)") then
            for i,player in pairs(getElementsByType("player")) do
                if getElementData(player,"player:data") then
			if getElementData(player,"player:data").uid == result[1].id then
                exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto błąd\n#ffffffKtoś jest już zalogowany na to konto.","error",4000)
                cancelEvent()
			return
			end
        end
            end
            local resultlvl=exports["cmta-db"]:dbGet("SELECT * FROM cmta_levels WHERE level=?",result[1].level)

            setPlayerName(client, login)
            setElementModel(client,result[1].skin)
            setElementData(client,"player:data", {
               uid = result[1].id,
               points = result[1].points,
               gainscore = result[1].gainscore,
               timemultiplier = result[1].timemultiplier,
               timeplayed = result[1].timeplayed,
               lvl = result[1].level,
               exp = result[1].exp,
               PO = result[1].PO,
               dailyclicks = result[1].dailyclicks,
               requestexp = resultlvl[1].requestexp,
               weapons = result[1].weapons,
               currentplaytime = 0,
               limitveh = result[1].limitveh,
               logged = true
            })
         --   setElementData(client, "player:uid", result[1].id)
        --    setElementData(client, "player:points", result[1].points)
           -- setElementData(client, "player:gainscore", result[1].gainscore)
           -- setElementData(client, "player:timemultiplier", result[1].timemultiplier)
           -- setElementData(client, "player:timeplayed", result[1].timeplayed)
           -- setElementData(client, "player:lvl", result[1].level)
          --  setElementData(client, "player:exp", result[1].exp)
          --  setElementData(client, "player:po", result[1].PO)
           -- setElementData(client, "player:dailyclicks", result[1].dailyclicks)
           -- local resultlvl=exports["cmta-db"]:dbGet("SELECT * FROM cmta_levels WHERE level=?",result[1].level)
         --   setElementData(client,"player:requestexp",tonumber(resultlvl[1].requestexp))
        --    setElementData(client,"player:zalogowany",true)
       --     setElementData(client,"player:logged",true)
       --     setElementData(client,"player:currentplaytime",0)
       --     setElementData(client,"player:weapons",result[1].weapons)

            if getPlayerSerial(client) ~= result[1].serial then
                triggerClientEvent(client, "cmta_login:pin", resourceRoot)
            else
                triggerClientEvent(client, "cmta_login:succeslogin", resourceRoot)
            end

            
            local resultachievement=exports["cmta-db"]:dbGet("SELECT * FROM cmta_achievements WHERE uid=?",result[1].id)
            if resultachievement and #resultachievement < 1 then
            exports["cmta-db"]:dbSet("INSERT INTO cmta_achievements (uid) VALUES (?)", result[1].id)
            exports["cmta-db"]:dbSet("INSERT INTO cmta_inventory (uid) VALUES (?)",result[1].id)
            end
            --setElementData(client,"player:achievements",result[1].achievements)
            local data = getElementData(client,"player:data")
            local lvl = data.lvl
            if lvl >= 50 and lvl < 100 then 
            setPedStat(client, 24, 612)
            setElementHealth(client,110)
            elseif lvl >= 100 and lvl < 150 then 
            setPedStat(client, 24, 652)
            setElementHealth(client,120)
            elseif lvl >= 150 and lvl < 200 then 
            setPedStat(client, 24, 700)
            setElementHealth(client,130)
            elseif lvl >= 200 and lvl < 250 then 
            setPedStat(client, 24, 740)
            setElementHealth(client,140)
            elseif lvl >= 250 and lvl < 300 then 
            setPedStat(client, 24, 783)
            setElementHealth(client,150)
            elseif lvl >= 300 and lvl < 350 then 
            setPedStat(client, 24, 830)
            setElementHealth(client,160)
            elseif lvl >= 350 and lvl < 400 then 
            setPedStat(client, 24, 870)
            setElementHealth(client,170)
            elseif lvl >= 400 and lvl < 450 then 
            setPedStat(client, 24, 913)
            setElementHealth(client,180)
            elseif lvl >= 450 and lvl < 500 then 
            setPedStat(client, 24, 957)
            setElementHealth(client,190)
            elseif lvl >= 500 then
            setPedStat(client, 24, 1000)
            setElementHealth(client,200)
            end

            local premium=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE id=? AND premium>NOW() LIMIT 1", getElementData(client,"player:data").uid)
            if (premium and #premium > 0) then
                local data = getElementData(client,"player:data")
                data.vip = true
                setElementData(client,"player:data",data)
            end

            local gang=exports["cmta-db"]:dbGet("SELECT * FROM cmta_gang_members WHERE uid=?",result[1].id)
            if (gang and #gang > 0) then
                local data = getElementData(client,"player:data")
                data.gang = gang[1]["gang_name"]
                setElementData(client,"player:data",data)
            end

		    if getElementData(client,"player:data").weapons and getElementData(client,"player:data").weapons ~= "[ [ ] ]" then
			    for weapon, ammo in pairs(fromJSON(getElementData(client,"player:data").weapons)) do
			    	giveWeapon(client, weapon, ammo, true)
		    	end
	    	end

            exports["cmta-db"]:dbSet("update cmta_users set player_online=1 where id=?",getElementData(client,"player:data").uid)

else
       exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto nieprawidłowość!\n#ffffffPodane dane są nieprawidłowe.","error",4000)
        end
    else
        exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Przykro mi...\n#ffffffKonto o podanym loginie nie istnieje.","error",4000)
    end
end)

addEvent("cmta:register", true)
addEventHandler("cmta:register", resourceRoot, function(login,pass,pin,weblogin,webpassword,webemail)
    local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE login=?", login)
    if result and #result > 0 then
        triggerClientEvent(client, "cmta:regtext", resourceRoot, "#ff0000Login jest już zajęty")
    else
        local query=exports["cmta-db"]:dbSet("INSERT INTO cmta_users (login,password,pin,email,serial) VALUES (?,?,?,?,?)", login, teaEncode(pass,"R{e+=j8'a!EqUT7UKHJS,(E[txHjj35;9aP:l;QjNIpK0$r:Q)"),pin,webemail,getPlayerSerial(client))
        if query then
        triggerClientEvent(client, "cmta:regtext", resourceRoot, "#00ff00Pomyślnie stworzono konto")
        end
    end
end)

addEvent("cmta_login:checkPIN", true)
addEventHandler("cmta_login:checkPIN", resourceRoot, function(pin)
	local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE id=?", getElementData(client,"player:data").uid)
	if result[1].pin == tonumber(pin) then
	    triggerClientEvent(client, "cmta_login:succeslogin", resourceRoot)
	else
        exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto nieprawidłowość!\n#ffffffPodany kod PIN jest nieprawidłowy.","error",4000)
        return
	end
end)

addEvent("cmta_login:checkbonus", true)
addEventHandler("cmta_login:checkbonus", resourceRoot, function()
    exports["cmta-bonusdnia"]:check(client) 
end)

addEvent("cmta_login:checkban", true)
addEventHandler("cmta_login:checkban", resourceRoot, function()
    local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_bans WHERE serial=? and type=?", getPlayerSerial(client),"ban")
    if result and #result > 0 then
	    triggerClientEvent(client, "cmta_login:ban", resourceRoot,result)
    else
        triggerClientEvent(client, "cmta_login:ban", resourceRoot,"0")
    end
end)

addEvent("cmta_login:quit", true)
addEventHandler("cmta_login:quit", resourceRoot, function()
    kickPlayer(client)
end)

addEvent("cmta_login:spawnPlayer", true)
addEventHandler("cmta_login:spawnPlayer", resourceRoot, function()
    local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE id=?", getElementData(client,"player:data").uid)
    if result and #result > 0 then
        spawn=split(tostring(result[1].last_position), ",")
        spawnPlayer ( client, spawn[1],spawn[2],spawn[3])
        setElementInterior(client,spawn[4])
        setElementDimension(client,spawn[5])
    end
end)

local allowed = { { 48, 57 }, { 65, 90 }, { 97, 122 } } -- numbers/lowercase chars/uppercase chars

function generateString ( len )
    
    if tonumber ( len ) then
        math.randomseed ( getTickCount () )

        local str = ""
        for i = 1, len do
            local charlist = allowed[math.random ( 1, 3 )]
            str = str .. string.char ( math.random ( charlist[1], charlist[2] ) )
        end

        return str
    end
    
    return false
    
end


local recovery_players = {}

addEvent("cmta_login:recovery_password", true)
addEventHandler("cmta_login:recovery_password", resourceRoot, function(login,email,pin)
	local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE login=? and email=? and pin=?", login,email,pin)
    if result and #result > 0 then
    realTime=getRealTime()
	local r = realTime.year+1900
	local m = realTime.month+1
	local t = realTime.monthday
	local data=string.format("%04d-%02d-%02d %02d:%02d:%02d", r, m, t,realTime.hour, realTime.minute, realTime.second)
    for i, v in pairs ( recovery_players ) do
    if tostring(v[1]) == getPlayerSerial(client) then
    if tostring(v[2]) < data then
        table.remove(v)
        outputChatBox("usunieto")
    else
        cancelEvent()
        exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Zwolnij...\n#ffffffMusisz odczekać 10 minut przed wysłaniem\nkolejnego e-maila.","info",4000)

        return
    end
    end
    end
    table.insert( recovery_players, {getPlayerSerial(client),string.format("%04d-%02d-%02d %02d:%02d:%02d", r, m, t,realTime.hour, realTime.minute+10, realTime.second)})
    local hash = generateString ( 10 )
    local password = exports["cmta-db"]:dbSet("UPDATE cmta_users SET secret_table=? WHERE login=?",hash,login)
    if password then
    local result2=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE login=? and email=? and pin=?", login,email,pin)
    if result2 and #result2 > 0 then
		local sendto = email
        local message = "<center><img style='width: 200px; height: 200px;' src='https://i.imgur.com/ewZ7udN.png' /><br /><br /><span style='font-size: xx-large;'>Witaj "..login.."</span><br /><br />Weryfikacja informacji na temat twojego konta przebiegła pomyślnie. <br /><br />Twój kod do zmiany hasła to: "..result2[1]["secret_table"].." <br /><br /><br /><em><span style='font-size: small;'>Jeśli to nie ty resetowałeś hasło zgłoś to do <span style='color: #ff2828;'>administracji serwera</span> podając informacje z dolnej części wiadomości. Dbaj o bezpieczeństwo swojego konta.</span></em><br /><br />Staramy sie pomagać jak tylko potrafimy<br /><em><span style='color: #dd6b20;'>Ekipa ClickerMTA</span></em><br><br><center><span style='font-size: xx-small;'>O zmianę hasła zawnioskowano z poniższych danych</span></center><center><span style='font-size: xx-small;'>Serial: "..getPlayerSerial(client).."</span></center><center><span style='font-size: xx-small;'>IP: "..getPlayerIP(client).."</span></center>"
        sendCustomMail(sendto,message)
        exports['cmta-notyfikacje']:sendNotification(client,"#ccc000Informacja\n#ffffffKod weryfikacjny został wysłany na e-mail, \nszukaj go również w folderze SPAM!","info",5000)

        triggerClientEvent(client, "cmta_login:create_recovery", resourceRoot,login)
    else
    end
    end
    else
        exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto nieprawidłowość!\n#ffffffPodane informacje są niezgodne z kontem.","error",4000)
    end
end)


function sendCustomMail(sendto, mail)
    callRemote("https://panel.clickermta.pl/mailer.php", returns,sendto, mail)

end

function returns(msg, num)
	if msg == "ERROR" or (not msg) then
	else
	end
end

addEvent("cmta_login:change_password", true)
addEventHandler("cmta_login:change_password", resourceRoot, function(login,code,pass)
	local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE login=? and secret_table=?", login,code)
    if result and #result > 0 then
    exports["cmta-db"]:dbSet("UPDATE cmta_users SET password=?, secret_table=? WHERE login=?",teaEncode(pass,"R{e+=j8'a!EqUT7UKHJS,(E[txHjj35;9aP:l;QjNIpK0$r:Q)"),"",login)
    exports['cmta-notyfikacje']:sendNotification(client,"#00ff00Sukces!\n#ffffffHasło do konta "..login.." \nzostało pomyślnie zmienione.","success",4000)
    triggerClientEvent(client, "cmta_login:create_loginpanel", resourceRoot)    
    else
    exports['cmta-notyfikacje']:sendNotification(client,"#FF0000Wykryto nieprawidłowość!\n#ffffffKod weryfikacyjny nie jest poprawny.","error",4000)
    
end
end)